package cn.myweixin.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Properties;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.myweixin.po.AccessToken;
import cn.myweixin.po.menu.Menu;
import net.sf.json.JSONObject;

public class WeixinUtil {
	private static final String  APPID="wx1341463c2dca02ba";
	private static final String  APPSECRET="7679103275a4ac992a3a834655ea2c90";
	private static final String ACCESS_TOKEN_URL ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public static final String menu_create_url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	public static final String menu_delete_url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	private static String FileName = "access_token.properties";
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class); 
	/**
	 * get璇锋眰
	 * @param url
	 * @return
	 */
	public synchronized static JSONObject  doGetStr(String  url){
	
		DefaultHttpClient httpClient=new DefaultHttpClient();
		HttpGet httpGet=new HttpGet(url);
		JSONObject jsonObject=null;
		try {
			HttpResponse response=httpClient.execute(httpGet);
			HttpEntity entity=  response.getEntity();
			if(entity!=null){
				String result=EntityUtils.toString(entity,"UTF-8");
				jsonObject=JSONObject.fromObject(result);
			}
				
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		httpGet.releaseConnection();//释放链接
		return jsonObject;
	}
	
	
	/**
	 * post璇锋眰
	 * @param url
	 * @param outStr
	 * @return
	 */
	
	public static JSONObject doPostStr(String url, String outStr) {
		
		DefaultHttpClient client=new DefaultHttpClient();
		HttpPost httpPost=new HttpPost(url);
		JSONObject jsonObject=null;
		try {
			httpPost.setEntity(new StringEntity(outStr, "UTF-8"));
			HttpResponse response=client.execute(httpPost);
			String result=EntityUtils.toString(response.getEntity(), "UTF-8");
			jsonObject=JSONObject.fromObject(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return jsonObject;
		
	}
	
	
	/*public  static AccessToken getAccessToken(){
		
		AccessToken token=new AccessToken();
		String url=ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
		JSONObject jsonObject=doGetStr(url);
		if(jsonObject!=null){
			token.setToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInt("expires_in"));
			
		}
		
		return token;
	}*/
	
	
	public synchronized static String getAccessToken() {

	    try{
	    // 
	    Properties prop = new Properties();// 
	    InputStream fis  =WeixinUtil.class.getClassLoader().getResourceAsStream(FileName); 
	    
	    prop.load(fis);// 
	    fis.close();// 

	    String access_token = prop.getProperty("access_token");
	    String expires_in = prop.getProperty("expires_in");
	    String last_time = prop.getProperty("last_time");
	  
	    	
	    int int_expires_in = 0;
	    long long_last_time = 0;
	    try{
	        int_expires_in = Integer.parseInt(expires_in);
	        long_last_time = Long.parseLong(last_time);

	    }catch(Exception e){
	    	e.printStackTrace();
	    }
	    long current_time = System.currentTimeMillis();
	  
	    // 
	       if ((current_time - long_last_time) / 1000 >= int_expires_in) {
	            String url=ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
	    		JSONObject jsonObject=doGetStr(url);
	         
	           //淇濆瓨 
	            if(jsonObject!=null){
	            	  String  j_access_token = jsonObject.getString("access_token");
	   	             String  j_expires_in = String.valueOf( jsonObject.getInt("expires_in"));
	                prop.setProperty("access_token", j_access_token);     
	                prop.setProperty("expires_in", j_expires_in);     
	                prop.setProperty("last_time", System.currentTimeMillis()+"");    

	                URL url_ = WeixinUtil.class.getClassLoader().getResource(FileName);
	                FileOutputStream fos=  new FileOutputStream(new File(url_.toURI()));
	                prop.store(fos, null);
	                fos.close();// 鍏抽棴娴� 
	                return j_access_token;
	            }
	            
	        } else {
	            return access_token;
	        }
	    
	    }
	    catch(Exception e){
	       e.printStackTrace();
	    }
		return null;
	     
	}
	
	
	public static int createMenu(Menu menu) {  
	    int result = 0;  
	  
	    // 拼装创建菜单的url  
	    String url = menu_create_url.replace("ACCESS_TOKEN", getAccessToken());  
	    // 将菜单对象转换成json字符串  
	    String jsonMenu = JSONObject.fromObject(menu).toString();  
	    // 调用接口创建菜单  
	    JSONObject jsonObject =doPostStr(url, jsonMenu);
	  
	    if (null != jsonObject) {  
	        if (0 != jsonObject.getInt("errcode")) {  
	            result = jsonObject.getInt("errcode");  
	            log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
	        }  
	    }  
	  
	    return result;  
	}  
	
	
	public static int deletemenu(){
		
		int result=0;
		
		String url= menu_delete_url.replace("ACCESS_TOKEN", getAccessToken()); 
		JSONObject jsonObject=doGetStr(url);
		
		 if (null != jsonObject) {  
		        if (0 != jsonObject.getInt("errcode")) {  
		            result = jsonObject.getInt("errcode");  
		            log.error("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
		        }  
		    }  
		  
		    return result;
		
	}

}
